﻿namespace Digitalmes.Application.Sys.Roles.Commands;

/// <summary>
/// 给角色分配菜单命令。
/// </summary>
public record DistributeMenusToRoleCommand(long RoleId, long[] MenuIds) : IRequest<IResult<bool>>;

internal sealed class DistributeMenusToRoleCommandHandler(IRepository<SysRoleMenu> repo) : IRequestHandler<DistributeMenusToRoleCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(DistributeMenusToRoleCommand request, CancellationToken cancellationToken)
    {
        List<SysRoleMenu> roleMenus = request.MenuIds.Distinct().Select(menuId => new SysRoleMenu
        {
            RoleId = request.RoleId,
            MenuId = menuId,
        }).ToList();

        // 删除原有的映射关系
        await repo.DeleteAsync(m => m.RoleId == request.RoleId, cancellationToken);

        // 添加新的映射关系
        var result = await repo.InsertRangeAsync(roleMenus, cancellationToken);

        return Result.From(result);
    }
}
